package main

import (
	"cossbow.com/ms/util"
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
)

func main() {
	config := consulapi.DefaultConfig()
	config.Address = "127.0.0.1:8500"
	client, er := consulapi.NewClient(config)
	util.ThrowException(er)

	KV := client.KV()
	pair := &consulapi.KVPair{Key: "user", Value: []byte("cossbow"),}
	meta, er := KV.Put(pair, &consulapi.WriteOptions{})
	util.ThrowException(er)
	fmt.Println(meta)

	serviceName := "false-service"
	host := "127.0.0.1"
	port := 7777
	serviceId := generateServiceId(serviceName, host, port)
	reg := &consulapi.AgentServiceRegistration{
		ID:      serviceId,
		Name:    serviceName,
		Tags:    []string{serviceName},
		Address: host,
		Port:    port,
		Check: &consulapi.AgentServiceCheck{
			GRPC:     fmt.Sprintf("%s:%d/%s", host, port, serviceName),
			Interval: "3s",
		},
	}

	Agent := client.Agent()
	er = Agent.ServiceRegister(reg)
	util.ThrowException(er)

	er = Agent.ServiceDeregister(serviceId)
	util.ThrowException(er)

}

func generateServiceId(name, host string, port int) string {
	return fmt.Sprintf("%s-%s-%d", name, host, port)
}
